import { off } from "process";

// 事件类  
// 设计模式 发布订阅
interface EventType {
	[propName: string]: (() => void)[]
}

export class Event {
	event: EventType = {}
	// 绑定事件
	on(type: string, callback: () => void) {
		if (this.event[type]) {
			this.event[type].push(callback)
		} else {
			this.event[type] = [callback]
		}
	}
	// 触发事件
	emit(type: string) {
		if (this.event[type]) {
			this.event[type].forEach(callback => {
				callback()
			})
		}
	}
	// 解除绑定
	off(type: string, callback?: () => void) {
		if (callback && this.event[type]) {
			this.event[type] = this.event[type].filter(v => v !== callback)
		} else if (!callback && this.event[type]) {
			delete this.event[type]
		} else {
			console.warn('未找到自定义事件' + type, '所以无法删除改事件')
			// throw new Error('未找到自定义事件' + type + ',所以无法删除改事件')
		}
	}
}


const ev = new Event();

ev.on('click', () => {
	console.log('触发click 的自定义事件1')
})

const fn2 = () => {
	console.log('触发click 的自定义事件2')
}

ev.on('click', fn2)

ev.on('qwe', () => {
	console.log('触发qwe的自定义事件3')
})



ev.emit('click')

ev.off('click', fn2)

ev.emit('click')

ev.emit('qwe')

